import React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import { View, Text } from "@tarojs/components"
import MoveArea from "@/components/moveArea";
import VoiceRecorder from "./voice-recorder";
import { uploadFile } from "@/request/upload";
import { HideLoading, ShowLoading, ShowToast, ToPage, VibrateShort } from "@/utils";
import BillForm from "@/components/billForm";
import viewMode from "@/store/viewMode";
import { billType } from "@/types";
import account from "@/store/account";
import user from "@/store/user";

const BillInsert = React.forwardRef<
    {
        openBillFormHand: (bill: billType) => void
    },
    {
        date: string,
        onRefresh: (data: billType) => void
    }>((props, ref) => {
        const [voiceRecorderVisible, setVoiceRecorderVisible] = useState(false)
        const [autoIdentify, setAutoIdentify] = useState(false)
        const [location, setLocation] = useState<{ clientX: number, clientY: number } | null>({ clientX: 0, clientY: 0 })
        const [clickDown, setClickDown] = useState(false)
        const [formVisible, setFormVisible] = useState(false)
        const [bill, setBill] = useState<billType>({})

        const billInit = useMemo(() => {
            return {
                date: props.date,
                note: '',
                type: 0,
                payeeId: 0,
                accountId: account.activeAccount?.id,
                userId: user.info?.id
            }
        }, [props])

        const openVoiceRecorder = () => {
            VibrateShort()
            refRecord.current.start()
            setVoiceRecorderVisible(true)
        }

        const handleMove = (e) => {
            const { clientX, clientY } = e.touches[0]
            if (voiceRecorderVisible) {
                setLocation({ clientX, clientY })
            }
        }

        const refRecord = useRef<{
            start: () => void,
            stop: () => void
        }>({
            start: () => { },
            stop: () => { }
        })
        const refDate = useRef<{ date: string }>({
            date: ''
        })

        const touchStart = () => {
            setClickDown(true)
            setLocation(null)
        }
        const recordEnd = () => {
            setClickDown(false)
            setVoiceRecorderVisible(false)
            refRecord.current.stop()
        }
        const recordFinish = (tempFilePath) => {
            const vcUrl = {
                // 讯飞
                xf: '/vc/voiceToText',
                // 阿里
                ali: '/vc/aliVoiceToText'
            }
            setAutoIdentify(true)
            ShowLoading('解析中...')
            uploadFile(vcUrl.xf, tempFilePath).then(res => {
                if (!res.data) {
                    ShowToast('未识别到内容，请手动输入')
                } else {
                    HideLoading()
                }
                // props.date不知道为何会被重置为空字符串
                showBillForm({
                    note: res.data || '',
                    date: refDate.current.date
                })
            }).catch(_ => {
                ShowToast('语音识别失败，请重试')
            })
        }

        // 打开手动输入
        const openBillFormHand = (obj?: billType) => {
            setAutoIdentify(false)
            showBillForm(obj, true)
        }
        useImperativeHandle(ref, () => {
            return {
                openBillFormHand
            }
        })

        const showBillForm = (obj?: billType, isForce?: boolean) => {
            if (viewMode.recordType === 'form' || obj?.id) {
                setBill(obj ? {
                    ...billInit,
                    ...obj
                } : {
                    ...billInit
                })
                VibrateShort()
                setFormVisible(true)
            } else if (obj?.note || isForce) {
                ToPage(`/pages/chat/index?text=${obj?.note || ''}`)
            }
        }

        const closeModal = () => {
            setBill({
                ...billInit,
                note: ''
            })
            setFormVisible(false)
            setAutoIdentify(false)
        }

        const saveBill = (res) => {
            props.onRefresh(res)
            closeModal()
        }

        useEffect(() => {
            viewMode.setBehind(formVisible || voiceRecorderVisible, true)
            refDate.current.date = props.date
        }, [formVisible, voiceRecorderVisible])

        return <View className="insert-com">
            <MoveArea disabled={voiceRecorderVisible}>
                {
                    user.info?.id ?
                        <View className={"page-add-btn flex-column flex-center" + (clickDown ? ' click-down' : '')}
                            onClick={() => openBillFormHand()}
                            onLongPress={openVoiceRecorder}
                            onTouchStart={touchStart}
                            onTouchMove={handleMove}
                            onTouchEnd={recordEnd}
                        >
                            <View id="guide-btn" className="add-btn-item type-item flex-column flex-center">
                                <Text className="iconfont hide-animate icon-yuyin2"></Text>
                                <View className="font-size24">去记账</View>
                            </View>
                        </View> :
                        <View className={"page-add-btn flex-column flex-center" + (clickDown ? ' click-down' : '')}
                            onClick={() => ToPage('/pages/login/index')}
                            onTouchEnd={recordEnd}
                            onTouchStart={touchStart}
                        >
                            <View id="guide-btn" className="add-btn-item type-item flex-column flex-center">
                                <Text className="iconfont hide-animate icon-ai"></Text>
                                <View className="font-size24">去登录</View>
                            </View>
                        </View>
                }
            </MoveArea>
            <VoiceRecorder
                ref={refRecord}
                visible={voiceRecorderVisible}
                onFinish={recordFinish}
                location={location}></VoiceRecorder>
            <BillForm
                autoIdentify={autoIdentify}
                visible={formVisible}
                onClose={closeModal}
                onSure={saveBill}
                bill={bill}>
            </BillForm>
        </View>
    })

export default BillInsert
